package org.truenewx.tnxjee.repo.jdbc.util;

import jakarta.validation.constraints.NotNull;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;
import org.truenewx.tnxjee.core.Strings;

/**
 * 条件表达式
 *
 * @author jianglei
 */
public class ConditionExpression {

    private String fieldName;
    private Comparison comparison;
    private String value;

    private ConditionExpression(String fieldName) {
        Assert.isTrue(StringUtils.isNotBlank(fieldName), "The fieldName cannot be blank");
        this.fieldName = fieldName;
    }

    public ConditionExpression(String fieldName, Comparison comparison, String value) {
        this(fieldName);
        this.comparison = comparison == null ? Comparison.EQUAL : comparison;
        Assert.isTrue(StringUtils.isNotBlank(value), "The value cannot be blank");
        this.value = value;
    }

    public ConditionExpression(String fieldName, String value) {
        this(fieldName, null, value);
    }

    public static ConditionExpression isNull(String fieldName) {
        ConditionExpression expression = new ConditionExpression(fieldName);
        expression.comparison = Comparison.IS_NULL;
        return expression;
    }

    public static ConditionExpression isNotNull(String fieldName) {
        ConditionExpression expression = new ConditionExpression(fieldName);
        expression.comparison = Comparison.NOT_NULL;
        return expression;
    }

    @NotNull
    public String getFieldName() {
        return this.fieldName;
    }

    @NotNull
    public Comparison getComparison() {
        return this.comparison;
    }

    public String getValue() {
        return this.value;
    }

    public String toString(boolean withFieldName) {
        String s = withFieldName ? this.fieldName : Strings.EMPTY;
        s += this.comparison.toQlString();
        if (this.comparison.isMultiple()) {
            return s + Strings.LEFT_BRACKET + this.value + Strings.RIGHT_BRACKET;
        }
        if (!this.comparison.isUnary()) {
            s += this.value;
        }
        return s;
    }

    @Override
    public String toString() {
        return toString(true);
    }

}
